<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.username"
        class="filter-item"
        clearable
        placeholder="用户名称"
        style="width: 150px;"
        @keyup.enter.native="handleFilter"
      />
      <el-button
        v-permission="['sys:user:list']"
        v-waves
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >搜索</el-button>
      <el-button
        v-permission="['sys:user:save']"
        v-waves
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreate"
      >添加</el-button>
    </div>

    <el-table :key="tableKey" :data="list" fit highlight-current-row style="width: 100%;">
      <el-table-column label="ID" prop="id" width="70px" align="center" />
      <el-table-column label="用户名称" prop="username" width="90px" align="center" />
      <el-table-column label="真实姓名" prop="name" width="90px" align="center" />
      <el-table-column label="所属部门" prop="deptName" align="center" />
      <el-table-column label="邮箱" prop="email" width="130px" align="center" />
      <el-table-column label="手机号" prop="mobile" width="100px" align="center" />
      <el-table-column label="状态" prop="statusDescribe" width="60px" align="center">
        <template slot-scope="{row}">
          <el-tag size="small" :type="row.status === 0 ? 'danger' : ''">{{ row.statusDescribe }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createdAt" width="140px" align="center" />
      <el-table-column label="操作" align="center" fixed="right" width="150px">
        <template slot-scope="{row}">
          <el-button
            v-waves
            v-permission="['sys:user:update']"
            type="primary"
            icon="el-icon-edit"
            @click="handleUpdate(row)"
          />
          <el-button
            v-waves
            v-permission="['sys:user:delete']"
            type="danger"
            icon="el-icon-delete"
            @click="handleDelete(row)"
          />
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNo"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />

    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      top="2vh"
      width="500px"
    >
      <el-form
        ref="dataForm"
        :model="user"
        :rules="rules"
        label-position="right"
        label-width="100px"
        style="width:90%"
      >
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="user.username" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="name">
          <el-input v-model="user.name" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="所属部门" prop="deptId">
          <el-cascader
            v-model="user.deptId"
            :options="deptList"
            :props="defaultProps"
            clearable
            :show-all-levels="false"
            style="width:310px"
            @change="changeDeptList"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="user.password" placeholder="请输入密码，如不修改不必填写" type="password" />
        </el-form-item>
        <br />
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="user.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="user.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="角色" prop="roleIdList">
          <el-select v-model="user.roleIdList" multiple placeholder="请选择角色" style="width:100%">
            <el-option
              v-for="role in roleList"
              :key="role.id"
              :label="role.roleName"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <DictRadio v-model="user.status" type="system_status" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-waves @click="dialogFormVisible = false">取消</el-button>
        <el-button
          v-waves
          type="primary"
          @click="dialogStatus==='create'?createData():updateData()"
        >确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getList, get, create, update, del } from '@/api/system/user'
import { getRoleList } from '@/api/system/role'
import { getDeptList } from '@/api/system/dept'
import waves from '@/directive/waves' // Waves directive
import DictRadio from '@/components/DictRadio'
import {} from '@/utils'

export default {
  name: 'UserTable',
  directives: { waves },
  components: { DictRadio },
  filters: {},
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listQuery: {
        pageNo: 1,
        pageSize: 10,
        orderByField: 'createdAt',
        orderBy: 'desc'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '更新',
        create: '新增'
      },
      roleData: [],
      roleList: [],
      deptList: [],
      user: {
        status: 1,
        deptId: null,
        roleIdList: []
      },
      rules: {
        username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
        password: [
          {
            required: true,
            validator: (rule, value, callback) => {
              //此处是密码复杂度校验,暂时注释掉
              //var strlc = /^(?:(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^A-Za-z0-9]))(?=^[^\u4e00-\u9fa5]{0,}$).{8,20}$/
              if (this.user.id == null && value == null) {
                callback('请输入密码')
              } else if 
              (value != null && value.length<6 )
             // (value != null && value.match(strlc) == null)
              
               {
                callback(
                  new Error(
                    '密码必须大于6位数'
                    //'密码过于简单有被盗风险，请保证密码大于8位，并且由大小写字母、数字，特殊符号组成'
                  )
                )
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        name: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
        email:  '',    // [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
        deptId: [{ required: true, message: '请选择部门', trigger: 'blur' }],
        roleIdList: [{ required: true, message: '请选择角色', trigger: 'blur' }]
      },
      defaultProps: {
        expandTrigger: 'hover',
        checkStrictly: true,
        emitPath: false,
        children: 'children',
        label: 'name',
        value: 'id'
      }
    }
  },
  created() {
    this.getList()
    this.getDeptList()
    this.getRoleList()
  },
  methods: {
    getRoleList() {
      getRoleList().then(response => {
        this.roleData = response
      })
    },
    changeDeptList(e) {
      this.user.roleIdList = []
      this.roleList = this.roleData[e]
    },
    getDeptList() {
      getDeptList().then(response => {
        this.deptList = response
      })
    },
    // 获取数据
    getList() {
      getList(this.listQuery).then(response => {
        this.list = response.list
        this.total = response.totalCount
      })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    resetTemp() {
      this.$nextTick(() => {
        this.user = {
          status: 1,
          roleIdList: []
        }
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleCreate() {
      this.rules.password[0].required = true
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.resetTemp()
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          create(this.user).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.rules.password[0].required = false
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.resetTemp()
      get(row.id).then(response => {
        this.user = response
        this.roleList = this.roleData[response.deptId]
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          update(this.user).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del([row.id]).then(response => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      })
    }
  }
}
</script>
